<?php
namespace App\Http\Controllers\Api\Repositories;

use App\Models\Posts\WxComment;
use App\Models\Posts\WxPost;
use App\Models\WxCommentLike as Model;
use App\Models\User\WxUser;
use App\Wen\Utils\FieldUtils;
use App\Wen\Utils\UserUtils;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class WxCommentLikeRepositores
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;

    /**
     * 点赞
     */
    public static function like($uid, $comment_id)
    {
        DB::beginTransaction();
        try {
            $comment_modal = WxComment::where('id', $comment_id)->first();
            $comment_user_id = $comment_modal->user_id;

            $likeIsExists = Model::where('user_id',$uid)
                ->where('comment_id',$comment_id)->exists();
            // 判断是否已经点过赞
            if($likeIsExists){
                return true;
            }
            $post_id = $comment_modal->posts_id;


            $CommentLikeModel = new Model();
            $CommentLikeModel->user_id = $uid;
            $CommentLikeModel->comment_id = $comment_id;
            $CommentLikeModel->comment_user_id = $comment_user_id;
            $CommentLikeModel->save();


            $user = WxUser::where('id', $uid)->first(FieldUtils::userInfoColums());
            $comment = WxComment::where('id', $comment_id)->first();

            if($comment_user_id != $user['id']){
                UserUtils::add_user_notice(3003, $comment_user_id, '您的评论收到了一个喜欢', '「<a href="/pages/user/user?id='.$user['id'].'">'.$user['user_name'].'</a>」' . '喜欢了您的评论。', 101, $comment['posts_id']);
            }
            Cache::forget($uid.':islike:comment:'.$comment->id);
            Cache::forget('comment:likecount:'.$comment->id);
            Redis::sadd('realtime:post:set', $post_id);
            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return false;
        }

    }

    public static function unlike($uid, $comment_id)
    {
        DB::beginTransaction();
        try {
            Model::where('user_id',$uid)
                ->where('comment_id',$comment_id)->delete();
            $post_id = WxComment::where('id', $comment_id)->value('posts_id');
            Redis::sadd('realtime:post:set', $post_id);
            Cache::forget($uid.':islike:comment:'.$comment_id);
            Cache::forget('comment:likecount:'.$comment_id);
            DB::commit();
            return true;

        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return false;
        }
    }

}
